package cn.stronglink.assetmanage.business.repair.assetlist;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import Scaner.InfraredScanerFactory;
import Scaner.scan.IScanerListener;
import Scaner.scan.TimerInfraraedScaner;
import cn.stronglink.assetmanage.BaseActivity;
import cn.stronglink.assetmanage.MyApplication;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.repair.detail.RepairDetailActivity;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.SyncTypesDao;
import cn.stronglink.assetmanage.entity.MessageEvent;
import cn.stronglink.assetmanage.entity.OrderType;
import cn.stronglink.assetmanage.entity.RepailDetail;
import cn.stronglink.assetmanage.entity.Repair;
import cn.stronglink.assetmanage.entity.Room;
import cn.stronglink.assetmanage.entity.SyncTypes;
import cn.stronglink.assetmanage.entity.User;
import cn.stronglink.assetmanage.listener.ITaskSyncListener;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.LogUtil;
import cn.stronglink.assetmanage.utils.ToastUtil;
import cn.stronglink.assetmanage.utils.dao.BaseDataUtil;
import cn.stronglink.assetmanage.utils.dao.CheckDataUtil;
import cn.stronglink.assetmanage.utils.dao.RepairDataUtil;
import cn.stronglink.assetmanage.utils.net.TaskSyncModel;
import cn.stronglink.assetmanage.widget.CustomProgressDialog;

public class RepairDetailListActivity extends BaseActivity implements View.OnClickListener,
        ITaskSyncListener, IScanerListener {
    //单号，创建日期，总数
    private TextView tv_repair_order_no, tv_repair_order_create_date, tv_repair_total;
    //地点
    private Spinner spLocation;
    private TabLayout tl_repair_asset_list;
    private ViewPager vp_repair_asset_list;
    private RepairDetailVPAdapter mAdapter;
    private FragmentManager fm;
    private String[] mRepairTitle = MyApplication.APP_CONTEXT.getResources().
            getStringArray(R.array.repair);
    public static String orderNo = null;
    private List<RepailDetail> mAssetList = new ArrayList<>();
    //上传，完成保存
    private Button btn_upload_repair, btn_change_order_repaired, btn_scan_repair;
    private Repair mRepair;
    private TaskSyncModel mTaskSyncModel;
    private Dialog mCustomProgressDialog;
    //根据sn获取资产详情
    private Map<String, RepailDetail> searchAssetSnMap = new HashMap<>();
    //根据rfid获取资产详情
    private Map<String, RepailDetail> searchAssetRfidMap = new HashMap<>();
    private TimerInfraraedScaner scaner;
    private static final String TAG = "RepairDetailListActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_repair_detail_list);
        initDataAndView();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    private void initDataAndView() {
        initView();
        initData();
    }

    private void initView() {
        tv_repair_order_no = findViewById(R.id.tv_repair_order_no);
        tv_repair_order_create_date = findViewById(R.id.tv_repair_order_create_date);
        tv_repair_total = findViewById(R.id.tv_repair_total_count);
        spLocation = findViewById(R.id.sp_repair_location);
        tl_repair_asset_list = findViewById(R.id.tl_repair_asset_list);
        vp_repair_asset_list = findViewById(R.id.vp_repair_asset_list);
        btn_upload_repair = findViewById(R.id.btn_upload_repair);
        btn_upload_repair.setOnClickListener(this);
        btn_change_order_repaired = findViewById(R.id.btn_change_order_repaired);
        btn_change_order_repaired.setOnClickListener(this);
        btn_scan_repair = findViewById(R.id.btn_scan_repair);
        btn_scan_repair.setOnClickListener(this);
    }

    private void initData() {
        initOrderInfo();
        initViewPagerData();
        mTaskSyncModel = new TaskSyncModel();
        mTaskSyncModel.setListener(this);
        List<RepailDetail> repailDetailList = RepairDataUtil.getAllAssetByOrderNo(orderNo);
        if (repailDetailList != null) {
            for (RepailDetail repailDetail : repailDetailList) {
                searchAssetRfidMap.put(repailDetail.getRfidNo(), repailDetail);
                searchAssetSnMap.put(repailDetail.getSerialNo(), repailDetail);
            }
        }
    }

    private void initOrderInfo() {
        Intent intent = getIntent();
        if (intent != null) {
            orderNo = intent.getStringExtra(Constants.SEARCH_REPAIR_NO);
            if (orderNo != null) {
                //根据表单号获得巡检表单
                mRepair = RepairDataUtil.getRepairById(orderNo);
                String userId = User.getInstance().getId_();
                if (userId != null && !"".equals(userId)) {
                    mRepair.setOperatorBy(Long.valueOf(userId));
                }
                tv_repair_order_no.setText(mRepair.getId_());
                tv_repair_order_create_date.setText(mRepair.getCreateTime());
                mAssetList = RepairDataUtil.getAllAssetByOrderNo(orderNo);
                if (mAssetList != null) {
                    int total = mAssetList == null ? 0 : mAssetList.size();
                    tv_repair_total.setText(total + "");
                }
            } else {
                ToastUtil.toastShort("没有数据");
            }
        }
        List<Room> roomList = BaseDataUtil.getRoomList();
        ArrayAdapter<Room> roomArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, roomList);
        spLocation.setAdapter(roomArrayAdapter);
        spLocation.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Room room = (Room) spLocation.getSelectedItem();
                updateAssetData(room.getName());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void updateAssetData(String name) {
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setType(Constants.FIFTLER_REPAIR_DATA);
        String[] dataArr = new String[2];
        dataArr[0] = orderNo;
        dataArr[1] = name;
        messageEvent.setMessage(dataArr);
        EventBus.getDefault().post(messageEvent);
    }

    private void initViewPagerData() {
        mAssetList = RepairDataUtil.getAllAssetByOrderNo(orderNo);
        if (mAssetList != null) {
            int total = mAssetList == null ? 0 : mAssetList.size();
            tv_repair_total.setText(total + "");
        }
        fm = getSupportFragmentManager();
        if (orderNo != null) {
            List<RepailDetail> unRepairAssetList = RepairDataUtil.getunRepairAssetByOrderNo(orderNo);
            List<RepailDetail> repairedAssetList = RepairDataUtil.getRepairedAssetByOrderNo(orderNo);
            int unRepairSize = unRepairAssetList == null ? 0 : unRepairAssetList.size();
            int repairSize = repairedAssetList == null ? 0 : repairedAssetList.size();
            mRepairTitle = new String[]{"待维修(" + unRepairSize + ")",
                    "已维修(" + repairSize + ")"};
        }
        mAdapter = new RepairDetailVPAdapter(fm, mRepairTitle);
        vp_repair_asset_list.setAdapter(mAdapter);
        tl_repair_asset_list.setupWithViewPager(vp_repair_asset_list);
        tl_repair_asset_list.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                vp_repair_asset_list.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.btn_upload_repair:
                //上传本单
                uploadRepairOrder();
                break;
            case R.id.btn_change_order_repaired:
                //将维修单数据保存为已维修
                mAssetList = RepairDataUtil.getAllAssetByOrderNo(orderNo);
                mRepair.setStatus(Constants.STATUS_THREE);
                mRepair.setDetailList(mAssetList);
                mRepair.setOperatiorName(User.getInstance().getName());
                RepairDataUtil.saveRepairDetailata(mRepair);
                ToastUtil.toastShort("维修单状态更改完成");
                break;
            case R.id.btn_scan_repair:
                if (scaner != null) {
                    scaner.playSingle();
                }
                break;
            default:
                break;
        }
    }

    private void uploadRepairOrder() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("是否上传单中所有数据，上传成功后，本单中所有数据会删除。");
        builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                saveRepairDataWeb();
                dialog.cancel();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }


    private void saveRepairDataWeb() {
        if (mRepair != null) {
            mCustomProgressDialog = CustomProgressDialog.createLoadingDialog(this, getString(R.string.is_upload));
            mCustomProgressDialog.setCancelable(false);
            mCustomProgressDialog.show();
            mRepair = RepairDataUtil.getRepairData(mRepair);
            mTaskSyncModel.uploadRepair(mRepair);
        }
    }

    private void saveRepairData() {
        mRepair.setDetailList(mAssetList);
        mRepair.setStatus(Constants.STATUS_THREE);
        DaoManager.getDaoSession(this).getRepairDao().insertOrReplace(mRepair);
        onBackPressed();
    }


    @Override
    protected void onResume() {
        super.onResume();
        setSelectPosition(4);
        initData();
        initScaner();
    }

    private void initScaner() {
        this.scaner = new TimerInfraraedScaner(this);
        this.scaner.setScanerListener(this);
    }

    @Override
    public void onFail(String orderNo, OrderType orderType, Exception e, int sum) {
        if (mCustomProgressDialog != null) {
            mCustomProgressDialog.cancel();
        }
        ToastUtil.toastShort(getString(R.string.fail) + orderType + sum + e.getMessage());
    }

    @Override
    public void onSucces(String orderNo, OrderType orderType, int sum) {
        if (mCustomProgressDialog != null) {
            mCustomProgressDialog.cancel();
        }
        ToastUtil.toastShort(getString(R.string.success));
        //成功后，finish本页面
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if (mTaskSyncModel != null) {
                mTaskSyncModel.setListener(null);
                mTaskSyncModel = null;
            }
            if (scaner != null) {
                this.scaner.stop();
                this.scaner.destory();
            }
            if (mCustomProgressDialog != null) {
                mCustomProgressDialog.cancel();
            }
            EventBus.getDefault().unregister(this);
        } catch (Exception e) {
            LogUtil.e(TAG, e.getMessage());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdateData(MessageEvent messageEvent) {
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    @Override
    public void onScaning(List<String> data) {
        if (data != null && data.size() > 0) {
            String sn = data.get(data.size() - 1);
            this.pushSn(sn);
        }
    }

    private void pushSn(String sn) {
        sn = replaceBlank(sn);
        //判断扫描到的sn或者rfid是否在数据库中
        if (searchAssetSnMap.containsKey(sn)) {
            // 在数据库中存在,跳转到详情页，有sn号
            showRepairDetailActivity(sn);
        } else if (searchAssetRfidMap.containsKey(sn)) {
            //跳转到详情页，有rfid号
            showRepairDetailActivity(sn);
        } else {
            ToastUtil.toastShort("扫描的数据在本单中不存在");
        }
    }

    /**
     * 去掉字符串中\R等
     *
     * @param str
     * @return
     */
    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    private void showRepairDetailActivity(String sn) {
        Intent intent = new Intent(this, RepairDetailActivity.class);
        intent.putExtra(Constants.REPAIR_DETAIL_NO, sn);
        intent.putExtra(Constants.REPAIR_REGISTER_ORDER, orderNo);
        this.startActivity(intent);
    }

}
